package com.gitee.jmash.rbac.client.token;

import com.gitee.jmash.common.cache.SerialCache;
import com.gitee.jmash.common.grpc.auth.OAuth2Credentials;
import com.gitee.jmash.common.security.JmashPrincipal;
import com.gitee.jmash.rbac.client.RbacClientConfig;
import com.google.protobuf.StringValue;
import jakarta.enterprise.inject.spi.CDI;
import jmash.rbac.RbacGrpc;
import jmash.rbac.protobuf.TokenResp;

public class OrganUserAccessToken {

  /** 缓存. */
  public static SerialCache getCache() {
    return CDI.current().select(SerialCache.class).get();
  }

  public static String getKey(String tenant, String unifiedId) {
    return "organtoken:" + unifiedId + ":" + tenant;
  }

  public static String getClearKey(String unifiedId) {
    return "organtoken:" + unifiedId + ":*";
  }

  /** 清理用户组织AccessToken. */
  public static void clearOriginAccessToken(String unifiedId) {
    String clearKey = getClearKey(unifiedId);
    getCache().clearScan(clearKey);
  }

  /** 获取源访问Token. */
  public static String getOriginAccessToken(String tenant, JmashPrincipal principal) {
    String unifiedId = principal.getUnifiedId();
    // 源AccessToken.
    String originKey = getKey(tenant, unifiedId);
    if (getCache().containsKey(originKey)) {
      return (String) getCache().get(originKey);
    }
    return null;
  }

  /** 创建系统访问Token. */
  public static String getAccessToken(String originAccessToken, String tenant,
      JmashPrincipal principal) {
    String unifiedId = principal.getUnifiedId();
    String key = getKey(tenant, unifiedId);
    if (getCache().containsKey(key)) {
      return (String) getCache().get(key);
    }
    TokenResp token = loginOrgan(originAccessToken, tenant);
    String accessToken = token.getAccessToken();
    int expiresIn = token.getExpiresIn() - 300;
    //缓存源AccessToken
    putOriginAccessToken(originAccessToken, principal, expiresIn);
    // 组织AccessToken
    getCache().put(key, accessToken, expiresIn);
    return accessToken;
  }

  /** 源AccessToken 缓存. */
  public static void putOriginAccessToken(String originAccessToken, JmashPrincipal principal,
      int expiresIn) {
    // 源AccessToken
    String unifiedId = principal.getUnifiedId();
    String originKey = getKey(principal.getTenant(), unifiedId);
    getCache().put(originKey, originAccessToken, expiresIn);
    String originStorage = getKey(principal.getStorage(), unifiedId);
    getCache().put(originStorage, originAccessToken, expiresIn);
  }

  /** 组织用户登录. */
  public static TokenResp loginOrgan(String oldAccessToken, String tenant) {
    RbacGrpc.RbacBlockingStub rbacStub =
        RbacGrpc.newBlockingStub(RbacClientConfig.getManagedChannel())
            .withCallCredentials(new OAuth2Credentials(oldAccessToken));
    // GrpcChannel.getInProcessChannel() 本地调试
    return rbacStub.loginOrgan(StringValue.of(tenant));
  }

}
